<script setup>
import {reactive, ref} from 'vue'
import {FolderOpened, Folder, Plus, Delete, Edit, Search, Refresh} from "@element-plus/icons-vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";
import GroupDialog from "@/views/mgr/host/components/groupDialog.vue";
import SelectGroupDialog from "@/views/mgr/host/components/selectGroupDialog.vue";
import HostDialog from "@/views/mgr/host/components/hostDialog.vue";

const tableData = ref([])

const treeProps = reactive({
  checkStrictly: false,
})

const treeData = ref([])


const total = ref(0)

const queryForm = ref({
  query: '',
  pageNum: 1,
  pageSize: 10,
  group_id: 0
})

const groupDialogVisible = ref(false)
const groupDialogTitle = ref("")
const groupId = ref(-1)

const selectGroupDialogTitle = ref("")
const selectGroupDialogVisible = ref(false)

const hostDialogVisible = ref(false)
const hostDialogTitle = ref("")
const hostId = ref(-1)


const templateUrl = ref(process.env.VUE_APP_BASE_API + 'media/templates/主机导入模板.xlsx')

const verifyHost = async (id) => {
  try {
    console.log(id, '============id')
    const postData = {
      'all': id
    }
    const res = await requestUtil.post('host/host/verify', postData)
    const data = res.data
    if (data.code === 200) {
      ElMessage.success("验证成功")
    } else {
      ElMessage.error(data.msg)
    }
    await initTableData()
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const handleSelectGroupDialogValue = () => {
  selectGroupDialogTitle.value = '选择分组'
  selectGroupDialogVisible.value = true
}

const handleHostDialogValue = (id) => {
  if (id) {
    hostId.value = id;
    hostDialogTitle.value = '修改主机'
  } else {
    hostId.value = -1;
    hostDialogTitle.value = '添加主机'
  }
  hostDialogVisible.value = true
}

const handleGroupDialogValue = (id) => {
  if (id) {
    groupId.value = id;
    groupDialogTitle.value = '修改分组';
  } else {
    groupId.value = -1;
    groupDialogTitle.value = '添加分组'
  }
  groupDialogVisible.value = true
}

const initTableData = async (val) => {
  try {
    if (val) {
      if (val.id) {
        queryForm.value.group_id = val.id
      }
    }
    const res = await requestUtil.post('host/list', queryForm.value)
    const data = res.data
    if (data.code === 200) {
      tableData.value = data.msg
      total.value = data.total
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initTableData()

const handlePageChange = (pageNum) => {
  queryForm.value.pageNum = pageNum
  initTableData()
}

const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = pageSize
  initTableData()
}

const handleCurrentChange = async (val) => {
  await initTableData(val)
}

const initTreeData = async () => {
  try {
    const res = await requestUtil.get('host/group/list')
    const data = res.data
    if (data.code === 200) {
      treeData.value = data.msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initTreeData()

const handleGroupDelete = async (id) => {
  try {
    const res = await requestUtil.del('host/group/action', id)
    const data = res.data
    queryForm.value.group_id = 0
    if (data.code === 200) {
      await initTreeData()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const handleHostDel = async (id) => {
  try {
    const res = await requestUtil.del('host/host/action', {"id": id})
    const data = res.data
    // queryForm.value.group_id = 0
    if (data.code === 200) {
      await initTableData()
      await initTreeData()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const openTerminalPage = () => {
  window.open('/#/terminal', '_blank')
}
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card-hard">
          <template v-slot:header>
            <div class="space-between">
              <span>分组列表</span>
              <el-button dark @click="handleGroupDialogValue()" size="default" :icon="Plus" type="primary">
                新建
              </el-button>
            </div>
          </template>
          <el-table
              :data="treeData"
              :tree-props="treeProps"
              height="600px"
              row-key="id"
              default-expand-all
              :show-header="false"
              highlight-current-row
              @current-change="handleCurrentChange"
          >
            <el-table-column class="clearfix">
              <template #default="scope">
                <el-icon>
                  <FolderOpened v-if="Array.isArray(scope.row.children) && scope.row.children.length > 0"/>
                  <Folder v-else/>
                </el-icon>
                &nbsp;<span>{{ scope.row.name }}</span>
                <div style="float: right">
                  <span>{{ scope.row.count }}</span>
                  <el-button @click="handleGroupDialogValue(scope.row.id)" :icon="Edit" style="margin-left: 20px"
                             size="default"/>
                  <el-popconfirm title="你确定要删除该分组吗？" @confirm="handleGroupDelete(scope.row.id)">
                    <template #reference>
                      <el-button :icon="Delete" size="default" type="danger"/>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card class="box-card-hard">
          <template v-slot:header>
            <div class="space-between">
              <div>
                <span>服务器信息</span>
              </div>

              <div class="file-toolbar">
                <el-input clearable placeholder="IP/主机名称" v-model="queryForm.query"
                          style="max-width: 150px;" size="default"></el-input>

                <el-button size="default" :icon="Search" type="primary" @click="initTableData(queryForm.query)">搜索
                </el-button>

                <el-dropdown>
                  <el-button :icon="Plus" type="primary">
                    新建
                    <el-icon class="el-icon--right">
                      <arrow-down/>
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleHostDialogValue()">新增主机</el-dropdown-item>
                      <el-dropdown-item>
                        <el-link :href="templateUrl"
                                 :underline="false">下载模板
                        </el-link>
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleSelectGroupDialogValue()">
                        批量导入
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

                <el-popconfirm
                    title="你确定要进行主机验证:&nbsp; (全部|未成功部分) &nbsp;？"
                    confirm-button-text="全部"
                    cancel-button-text="部分"
                    width="200px"
                    confirm-button-type="danger"
                    cancel-button-type="warning"
                    @confirm="verifyHost(1)"
                    @cancel="verifyHost(0)"
                >
                  <template #reference>
                    <el-button :icon="Refresh" size="default" type="warning">验证</el-button>
                  </template>
                </el-popconfirm>

                <el-button style="margin-left: 0" size="default" type="danger" @click="openTerminalPage()">
                  <span role="img"><svg viewBox="64 64 896 896"
                                        focusable="false"
                                        data-icon="code" width="1em"
                                        height="1em" fill="currentColor"
                                        aria-hidden="true">
                    <path d="M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5
                        8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6
                        2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7
                        0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40
                        728H184V184h656v656z"></path></svg></span>

                  <span style="color: white">&nbsp;Web终端</span>
                </el-button>

                <!--                <el-button size="small" :icon="Plus">验证</el-button>-->
              </div>
            </div>
          </template>

          <el-table :data="tableData" stripe style="width: 100%;height: 600px">
            <el-table-column prop="hostname" label="主机名称" width="240"/>
            <el-table-column width="180" label="IP地址">
              <template v-slot="scope">
                <div v-if="scope.row.public_ip_addr">
                  <span class="public">公</span>
                  <span>{{ scope.row.public_ip_addr }}</span>
                </div>
                <div v-if="scope.row.private_ip_addr">
                  <span class="private">内</span>
                  <span>{{ scope.row.private_ip_addr }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="config_info" label="配置信息" width="240"/>
            <el-table-column prop="status" label="状态" width="80">
              <template v-slot="scope">
                <span v-if="scope.row.status === 0" class="el-tag el-tag--danger">验证失败</span>
                <span v-else-if="scope.row.status === 1" class="el-tag el-tag--warning">未验证</span>
                <span v-else class="el-tag el-tag--success">已验证</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="160"/>
            <el-table-column prop="update_time" label="更新时间" width="160"/>
            <el-table-column prop="remark" label="备注" width="240"/>
            <el-table-column prop="date" label="操作" width="240" fixed="right">
              <template v-slot="scope">
                <el-button @click="handleHostDialogValue(scope.row.id)" :icon="Edit" size="default"
                           type="primary"></el-button>
                <el-popconfirm title="你确定要删除这条主机信息吗？" @confirm="handleHostDel(scope.row.id)">
                  <template #reference>
                    <el-button :icon="Delete" size="default" type="danger"/>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <HostDialog v-model="hostDialogVisible" :tableData="tableData" :treeData="treeData"
                :dialogVisible="hostDialogVisible" :id="hostId"
                :dialogTitle="hostDialogTitle"
                @initTableData="initTableData" @initTreeData="initTreeData"/>

    <GroupDialog v-model="groupDialogVisible" :tableData="treeData" :dialogVisible="groupDialogVisible"
                 :id="groupId" :dialogTitle="groupDialogTitle" @initTreeData="initTreeData"/>

    <SelectGroupDialog v-model="selectGroupDialogVisible" :tableData="treeData"
                       :dialogVisible="selectGroupDialogVisible"
                       :dialogTitle="selectGroupDialogTitle" @initTreeData="initTreeData"
                       @initTableData="initTableData"/>
  </div>

  <el-pagination
      :hide-on-single-page="true"
      style="float: right;padding: 20px"
      v-model:currentPage="queryForm.pageNum"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
  />
</template>

<style scoped lang="scss">
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.file-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  /*  border-bottom: 1px solid #eee;*/
}

.space-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 24px;
}

.public {
  background: rgb(255, 231, 186);
  border-radius: 4px;
  color: rgb(51, 51, 51);
  margin-right: 4px;
  padding: 0 8px;
}

.private {
  background: rgb(186, 231, 255);
  border-radius: 4px;
  color: rgb(51, 51, 51);
  margin-right: 4px;
  padding: 0 8px;
}

.selected-row {
  background-color: #398dff; /* 选中行的背景色 */
}
</style>
